package com.pai.service;

import javax.swing.*;

import com.pai.entity.PaiTask;
import com.pai.entity.User;
import com.pai.entity.UserList;
import com.pai.gui.component.DownloadTaskCell;
import com.pai.gui.component.DownloadTaskListModel;
import com.pai.gui.component.UserIconList;
import com.pai.gui.component.WorkingTaskCell;
import com.pai.gui.component.WorkingTaskListModel;
import com.pai.service.SocketThread;

import java.util.*;
import java.io.*;
/**
 * 文件传输的监控线程，通过和cell动作控制的相连来完成对传输线程，显示panel的管理和调用
 * @author zhang
 *
 */
public class TransFileManager extends Thread {
    public TransFileManager() {
        try {
            jbInit();
        } catch (Exception ex) {
            ex.printStackTrace();
        }
    }

    private JPanel jtp;
   
    private WorkingTaskListModel uil;
    
    private DownloadTaskListModel dtlm;

    private boolean running = false;

    private ArrayList cellList = new ArrayList();

    private ArrayList threadList = new ArrayList();

    private Server s;

    int maxThreadNum = 5;

    int port=5000;

    /**
     * 构造函数
     * @param jtp 控件
     * @param uil 工作空间列表
     * @param dtlm
     */
    public TransFileManager(JPanel jtp , WorkingTaskListModel uil, DownloadTaskListModel dtlm) {
        this.jtp = jtp;
        this.uil = uil;
        this.dtlm = dtlm;
        s = new Server(threadList);
        SocketThread st;
        s.start();
    }
/**
 * 执行线程代码分为四种状态
 * 确认 传输 传输成功 传输失败
 * 
 */
    public void run() {
        running = true;
        SocketThread st;
        WorkingTaskCell wtc = null;
        //TransFilePanel tfp;
        int threadListSize;
        int cellListSize;
        int i = 0;
        int recevice = 0;
        while (running) {
            threadListSize = threadList.size();//socket线程的list。
            cellListSize = cellList.size();//middle item数量
          //  System.out.println(i);
	            for (i = 0; i < threadListSize; i++) {
	            	System.out.println("tfm: for : i="+i 
	            			+ " total:"+threadListSize + " celllistsize ="+cellListSize);
	            //获取线程列表中的文件传输线程
                st = (SocketThread) threadList.get(i);
                //通过轮询查看用户动作
                //此时如果middle panel中的用户数小于线程数，则需要添加一个用户信息进入panel
                if (cellListSize <= i) {
                	//发送端直接获取用户信息并在Middle panel中显示出用户信息
                	if(st.isFileSender()){
                		//显示task
                		uil.addCell(st.getTask());
                    	System.out.println("gettask"+st.getTask().getFileSize());
                    	System.out.println("uil->addcell");
                    	
                        try {
                            Thread.sleep(300);
                        } catch (InterruptedException ex2) {
                        }
                        //wtc = new WorkingTaskCell();
                        wtc = uil.getBl().getcell(i);
                        System.out.println("cell:"+ i+"  "+wtc.getFileName());
                       // jtp.addTab(st.getFileName(), tfp);
                        
                        cellList.add(wtc);
                        cellListSize ++;
                	}
                	//接受者检测是否非第一次轮询，如果不是将信息显示到Middle panel里面
                	else{
                		if( (st.getStatus()==SocketThread.FILE_TRANS_STATUS_CONTEXT)
                				||(st.getStatus() == SocketThread.FILE_TRANS_STATUS_SUCCESS)
                				||(st.getStatus() == SocketThread.FILE_TRANS_STATUS_FAIL)){
                			if(st.getTask().getFileName()!=null){
                				uil.addCell(st.getTask());
                				System.out.println("tfm: receiver: add cell:" + st.getTask().getFileName());
                		}
                			recevice = 0;
                        	System.out.println("uil->addcell");
                        	
                            try {
                                Thread.sleep(300);
                            } catch (InterruptedException ex2) {
                            }
                            
                            wtc = uil.getBl().getcell(i);
                           // jtp.addTab(st.getFileName(), tfp);
                            
                            cellList.add(wtc);
                            cellListSize ++;
                		}
                		//第一次作为接受者，新建用户信息的cell
                		else{
                			//第一次接受，middel没有cell。wtc目前为null；
                			//if(recevice == 0){
                				wtc = new WorkingTaskCell();
                    			//recevice++;
                			//}
                		}
                	}
                	
                   // tfp.jtaFileTransStatus.setText("文件发送  目标IP："+st.getIP()+"  端口："+st.getPort()+"\n\n正在与对方建立连接...");
                }
                //不需要添加panel时，直接通过cellist获取task的相关信息
                else{
                	 wtc = uil.getBl().getcell(i);
                	 System.out.println("else:"+ wtc.getFileName());
                	 
                }
                    //else {
//                    tfp = (TransFilePanel) paneList.get(i);
//                }
               // tfp.setStatus(st.getStatus());
                //检测传输是否取消，如果取消，终止传输但是不删除socket
                   if (wtc.isCancel()) {
                       st.cancelTrans();
                   }

                 //检测此时的socketthread状态
                switch (st.getStatus()) {
                case SocketThread.FILE_TRANS_STATUS_WAITFORCONFIRM: {
                    if (st.isFileSender()) {
                        //tfp.jtaFileTransStatus.setText(st.getFileTransMessage()+"\n\n连接成功！  等待对方回应...");
                    	//需要加入等待代码
                    } else {
                    	
                    	wtc.setSt(st);
                    	//新建实例
                    	PaiTask task  = new PaiTask();
                    	task.setBeginTime(new Date());
                    	task.setState("from");
                    	System.out.println("transfile : task.setFileSize(st.getTransFileLength()); = "+st.getTransFileLength());
                    	
                    	//作为接受者处于等待状态时弹出是否接收并获取储存位置
                    	wtc.JFPointOut();
                    	//补充task实例信息
                    	task.setFileSize(st.fileSize);
                    	task.setFileSrc(wtc.getFileName());
                    	task.setFileName(wtc.getFileRealName());
                    	task.setFromUser(UserList.getUserByIp(st.getIP())); 
                    	
                    	//将实例信息传入它对应的传输线程
                    	st.setTask(task);

                		//uil.addCell(task);
                    }
                    //断点续传
                    //判断是否确认接收，确认接收后查询是否存在临时文件，通过读临时文件实现断点续传的功能
                    if (wtc.isConfirm()) {
                        if(wtc.getFileName()!=null){
                            File aFile = new File(wtc.getFileName());
                            long off=0,size;
                            if (aFile.exists()) {
                                File temFile=new File(aFile.getAbsolutePath()+".tmp");
                                if(temFile!=null){
                                    try {
                                        DataInputStream dis=new DataInputStream(new
                                                FileInputStream(temFile));
                                        off = dis.readLong();
                                        System.out.println(off);
                                        size=dis.readLong();
                                        if(off!=new File(wtc.getFileName()).length()||size!=st.fileSize){
                                            off=0;
                                        }
                                    } catch (IOException ex1) {
                                        off=0;
                                    }
                                }
                            }
                            st.confirmReceiveFile(true,wtc.getFileName(),off);
                        }
                        else{
                            st.confirmReceiveFile(false,"",0);
                        }
                    }
                    else{
                    	if(wtc.isReject() == true){
                    		st.cancelTrans();
                    		threadList.remove(i);
                    	}
                    }
                    break;
                }
                //正在传输，显示进度条
                case SocketThread.FILE_TRANS_STATUS_CONTEXT: {
                    double progress = st.getTransFileLength() * 1.0 /
                                      st.fileSize * 100;
                    wtc.changeProgressbarValue((int) (progress));
//                    double transSpeed = (st.getTransFileLen gth() -
//                                         tfp.transFileLength) / 1024 * 2;
//                    tfp.transFileLength = st.getTransFileLength();
                    //tfp.jpgbFileTrans.setValue((int) progress);
                    //tfp.jtaFileTransStatus.setText(st.getFileTransMessage()+"\n\n");
                    //tfp.jtaFileTransStatus.setText(tfp.jtaFileTransStatus.getText()+"传输速度：" + (int) transSpeed + "k/s"+"  已完成：" + (int) progress +
                          //  "%");
                    break;
                }
                //传输成功删除cell和socketthread，并在rightpanel中添加一个显示的cell
                case SocketThread.FILE_TRANS_STATUS_SUCCESS: {
                    //tfp.jtaFileTransStatus.setText(st.getFileTransMessage()+"\n\n传输成功！");
                	System.out.println("传输成功！");
                    if(!st.isFileSender()){
                    	System.out.println("is file sender:" + wtc.getBean().getFileSrc());
                        new File(wtc.getBean().getFileSrc()+".tmp").delete();
                        PaiTask pai = st.getTask();
                        pai.setFileSize(st.getTransFileLength());
                    }
                    //if (wtc.isClosed()) {
                        threadList.remove(i);
                        cellList.remove(i);
                        uil.removeCell(i);
                        PaiTask temp = null;
                        if(dtlm.getAllCell().size()>0){
                            for(PaiTask pai : dtlm.getAllCell()){
                            	if( pai.getFileSrc().equals(st.getTask().getFileSrc()) )
                            		temp = pai;
                            }                          	
                        }
                        if(temp!=null){
                        	dtlm.removeCell(temp);
                        }

                        
                        dtlm.addCell(st.getTask());
                        i--;
                        threadListSize--;
                        cellListSize--;
                    //}
                    break;
                }
                //传输失败，删除cell和socketthread
                case SocketThread.FILE_TRANS_STATUS_FAIL: {
                	System.out.println("传输失败！");
                	if (wtc.isReject()) {
                        threadList.remove(i);
                   
                        i--;
                        threadListSize--;
                        //cellListSize--;
                        wtc.setReject(false);
                    }
                	else
                	{
                		if(wtc.isClosed()){
                			 threadList.remove(i);
                             uil.removeCell(i);
                             cellList.remove(i);
                             //jtp.remove(i);
                             i--;
                             threadListSize--;
                             cellListSize--;
                             //break;
                		}
                		
                		else if(wtc.isResend()){
                			sendFile(wtc.getBean());
                			threadList.remove(i);
                            uil.removeCell(i);
                            cellList.remove(i);
                            //jtp.remove(i);
                            i--;
                            threadListSize--;
                            cellListSize--;
                            //break;
                		}
                		else if(!st.isFileSender()){
                		//if(scandeleteFile(wtc, i)){
                			threadList.remove(i);
                            uil.removeCell(i);
                            cellList.remove(i);
                            boolean ifexist=false;
                            if(dtlm.getAllCell().size()>0){
                                for(PaiTask pai : dtlm.getAllCell()){
                                	if(pai.getFileSrc().equals(st.getTask().getFileSrc()))
                                		ifexist=true;
                                }                          	
                            }
                            if(!ifexist){
                            	dtlm.addCell(st.getTask());
/*                            	System.out.println("==============================================");
                            	System.out.println(st.getTask().getFileName()+" "+
                            			st.getTask().getFileSize()+" "+
                            			st.getTask().getFileSrc());
                            	System.out.println("==============================================");*/
                            }
                            
                            i--;
                            threadListSize--;
                            cellListSize--;
                		//}
//                		wtc.getBean().getFileSrc()
                	}
                	}
                	
                	wtc.setPlayBtnVisiable(true);
                    break;
                }
                }
            }
            try {
                Thread.sleep(500);
            } catch (InterruptedException ex) {
            }
        }
    }


/**
 * 文件发送方法
 * @param serverName 目标IP
 * @param port 目标端口	
 * @param fileName 发送文件名
 * @param message	发送附加信息
 * @param pai		发送相关实例
 */
	public void sendFile(String serverName, int port, String fileName,String message,PaiTask pai) {
        if (threadList.size() < maxThreadNum) {
            SocketThread st = new SocketThread(serverName, port, fileName,message,pai);
            System.out.println("new socketthread port = "+port+"servername = "+serverName);
            st.start();
            threadList.add(st);
        }
    }
	
	/**
	 * 文件发送方法
	 * 重发方法
	 * @param pai		发送已储存过的实例
	 */
public void sendFile(PaiTask pai){
	if (threadList.size() < maxThreadNum) {
        SocketThread st = new SocketThread(pai.getFromUser().getUserIP(), pai.getFromUser().getUserPort(), pai.getFileSrc(),null,pai);
        //System.out.println("new socketthread port = "+port+"servername = ");
        st.start();
        threadList.add(st);
	}
}

/**
 * 设置st端口
 * @param port		目标端口
 */

    public void setPort(int port) {
        s.stopThread();
        s = new Server(threadList);
        s.port = port;
        this.port=port;
        s.start();
    }

    /**
     * 设置允许的最大传输线程数
     * @param num
     */
    
    public void setMaxThreadNum(int num) {
        this.maxThreadNum = num;
        s.maxThreadNum=num;
    }
/**
 * 关闭传输方法
 */
    public void close(){
        s.stopThread();
        SocketThread st;
        for(int i=0;i<threadList.size();i++){
            st=(SocketThread)threadList.get(i);
            st.stopThread();
        }
    }
/**
 * 点击右上角的关闭键是完成tem文件的存储
 */
    public void quitsave(){
    	s.stopThread();
        SocketThread st;
        for(int i=0;i<threadList.size();i++){
            st=(SocketThread)threadList.get(i);
            st.setError("quit");
           // System.out.println("baocun");
            st.stopThread();
        }
    }
    /**
     * test
     * @param wtc
     * @param i
     * @return
     */
    public boolean scandeleteFile (WorkingTaskCell wtc, int i){
    	WorkingTaskCell tempwtc;
    	SocketThread tempst;
    	for (int j = 0; j < i ; j ++){
    		tempwtc = uil.getBl().getcell(j);
    		tempst = (SocketThread)threadList.get(j);
    		if (!tempst.isFileSender()){
    			if(wtc.getBean().getFileSrc().equals(tempwtc.getBean().getFileSrc())){
    				
                    return true;
    			}
    		}
    	}
    	return false;
    }

    
    private void jbInit() throws Exception {
    }
}
